<?php

namespace app\shop\model;

use app\BaseModel;
use app\channel\model\ChannelGoodsModel;
use app\channel\model\ChannelGoodsPricesModel;
use app\channel\model\ProxyLevelModel;
use app\channel\model\ProxyUserRegionModel;
use app\channel\model\ProxyUsersModel;
use app\channel\model\RewardModel;
use app\channel\model\StockDetailModel;
use app\channel\model\StockModel;
use app\channel\model\WalletModel;
use app\distribution\model\DividendModel;
use app\member\model\UsersModel;
use think\facade\Cache;
use think\Db;

use app\member\model\AccountLogModel;
use app\member\model\AccountModel;

//*------------------------------------------------------ */
//-- 订单表
/*------------------------------------------------------ */

class OrderModel extends BaseModel
{
    protected $table = 'shop_order_info';
    public $pk = 'order_id';
    protected $mkey = 'shop_order_mkey_';
    public $config = [];
    //供货代理商id
    public $supplyAgent = '';

    public function initialize()
    {
        parent::initialize();
        $this->config = config('config.');
    }
    /*------------------------------------------------------ */
    //-- 清除缓存
    /*------------------------------------------------------ */
    public function cleanMemcache($order_id = 0)
    {
        Cache::rm($this->mkey . $order_id);
        Cache::rm($this->mkey . '_goods_' . $order_id);
        if ($this->userInfo['user_id'] > 0) {
            Cache::rm($this->mkey . '_user_stat_' . $this->userInfo['user_id']);
        }
    }

    /*------------------------------------------------------ */
    //-- 获取会员订单信息汇总
    /*------------------------------------------------------ */
    public function userOrderStats($user_id = 0)
    {
        $user_id = $user_id * 1;
        $mkey = $this->mkey . '_user_stat_' . $user_id;
        $info = Cache::get($mkey);
        if (empty($info) == false) return $info;
        $where[] = ['order_type', 'IN', [0, 1]];
        $where[] = ['user_id', '=', $user_id];
        $where[] = ['order_status', 'in', [0, 1]];
        $info['all_num'] = $this->where($where)->count('order_id');//全部非取消订单
        unset($where);
        $where[] = ['order_type', 'IN', [0, 1]];
        $where[] = ['user_id', '=', $user_id];
        $where[] = ['is_pay', '=', 1];
        $where[] = ['order_status', '=', '0'];
        $where[] = ['pay_status', '=', '0'];
        $info['wait_pay_num'] = $this->where($where)->count('order_id');//待支付
        unset($where);
        $where[] = ['o.order_type', 'IN', [0, 1]];
        $where[] = ['o.user_id', '=', $user_id];
        $where[] = ['o.order_status', '=', '1'];
        $where[] = ['o.shipping_status', '=', '0'];
        $where[] = ['og.after_sale_num', '=', 0];
        //$info['wait_shipping_num'] = $this->where($where)->where("pay_status = 1 OR is_pay = 0")->count('order_id');//待发货
        $info['wait_shipping_num'] = Db::table('shop_order_info')->alias('o')
            ->leftJoin('shop_order_goods og', 'o.order_id = og.order_id')
            ->group('o.order_id')
            ->where($where)->count('o.order_id');

        unset($where);
        $where[] = ['order_type', 'IN', [0, 1]];
        $where[] = ['user_id', '=', $user_id];
        $where[] = ['order_status', '=', '1'];
        $where[] = ['shipping_status', '=', '1'];
        $info['wait_sign_num'] = $this->where($where)->count('order_id');//待签收
        Cache::set($mkey, $info, 30);
        return $info;
    }
    /*------------------------------------------------------ */
    //-- 生成订单编号
    /*------------------------------------------------------ */
    public function getOrderSn()
    {
        /* 选择一个随机的方案 */
        mt_srand((double)microtime() * 1000000);
        $date = date('Ymd');
        $order_sn = $date . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        $where[] = ['order_sn', '=', $order_sn];
        $where[] = ['add_time', '>', strtotime($date)];
        $count = $this->where($where)->count('order_id');
        if ($count > 0) return $this->getOrderSn();
        return $order_sn;
    }
    /*------------------------------------------------------ */
    //-- 获取订单信息
    /*------------------------------------------------------ */
    function info($order_id, $iscache = true, $isSaleAfter = true)
    {
        $cacheKey = $this->mkey . $order_id;
        if (!$isSaleAfter) $cacheKey = $this->mkey . 'no_after_sale_goods_' . $order_id;

        if ($iscache == true) {
            $info = Cache::get($cacheKey);
        }

        if (empty($info['order_id']) == true) {

            $admins = \think\facade\Session::get('main_admin');
            if ($admins['info']['warehouse_id'] != '' && $admins['info']['warehouse_id'] != 0) {
                $wheres[] = ['warehouse_id', 'in', $admins['info']['warehouse_id']];
            }

            $wheres[] = ['order_id', '=', $order_id];

            $info = $this->where($wheres)->find();

            if (empty($info)) return array();
            $info = $info->toArray();

            $orderGoods = $this->orderGoods($order_id, $isSaleAfter);
            $info['goodsList'] = $orderGoods['goodsList'];
            $info['afterSaleNum'] = $orderGoods['afterSaleNum'];
            $info['goodsNum'] = $orderGoods['goodsNum'];
            $info['isReview'] = $orderGoods['isReview'];
            $info['offlineimg'] = explode(',', $info['offlineimg']);
            $info['_add_time'] = dateTpl($info['add_time'], 'Y-m-d H:i:s', true);
            $info['_pay_time'] = dateTpl($info['pay_time'], 'Y-m-d H:i:s', true);
            $info['_cancel_time'] = dateTpl($info['cancel_time'], 'Y-m-d H:i:s', true);
            $info['_wait_pay_time'] = dateTpl($info['wait_pay_time'], 'Y-m-d H:i:s', true);
            $info['_shipping_time'] = dateTpl($info['shipping_time'], 'Y-m-d H:i:s', true);
            Cache::set($cacheKey, $info, 20);
        }

        $info['exp_price'] = explode('.', $info['order_amount']);

        $time = time();
        $info['isCancel'] = 0;
        $info['isPay'] = 0;
        $info['isDelete'] = 0;
        $info['isSign'] = 0;
        $info['isRefund'] = 0;
        $info['isAfterSale'] = 0;

        if ($info['is_split'] == 2) {//订单已拆分后，终止
            $info['ostatus'] = '已拆分';
            return $info;
        }

        if ($info['order_status'] == $this->config['OS_UNCONFIRMED']) {//订单未确定
            if ($info['is_pay'] > 0) {
                if ($info['pay_status'] == $this->config['PS_UNPAYED']) {
                    $info['isCancel'] = 1;//可操作：取消
                    $info['isPay'] = 1;//可操作：支付
                    $info['ostatus'] = '待付款';
                    $shop_order_auto_cancel = settings('shop_order_auto_cancel');
                    $is_cancel = false;
                    if ($info['order_type'] == 0 && $shop_order_auto_cancel > 0) {//下单时间，超过未付款的自动取消订单
                        $if_time = $info['cancel_time'] > $info['add_time'] ? $info['update_time'] : $info['add_time'];
                        $is_cancel = $if_time < $time - $shop_order_auto_cancel * 60;
                    } elseif ($info['order_type'] == 2 && $info['wait_pay_time'] > 0) {//拼团处理取消
                        $is_cancel = $info['wait_pay_time'] < $time;
                    }
                    if ($is_cancel == true) {
                        $isLook = redisLook('shop_order_cancel_' . $order_id);
                        if ($isLook == true) {
                            $upData['order_id'] = $order_id;
                            $upData['order_status'] = $this->config['OS_CANCELED'];
                            $upData['cancel_time'] = $time;
                            $res = $this->upInfo($upData, 'sys');
                            if ($res == true) {
                                $info['ostatus'] = '已取消';
                                $info['isCancel'] = 0;
                                $info['isPay'] = 0;
                            }
                        }
                    }
                } elseif ($info['pay_status'] == $this->config['PS_WAITCHACK']) {
                    $info['ostatus'] = '付款待审核';
                } elseif ($info['pay_status'] == $this->config['PS_CHACKERROR']) {
                    $info['ostatus'] = '付款审核失败';
                    $info['isCancel'] = 1;//可操作：取消
                    $info['isPay'] = 1;//可操作：支付
                }
            } else {
                $info['ostatus'] = '待确认';
                $info['isCancel'] = 1;//可操作：取消
            }
        } elseif ($info['order_status'] == $this->config['OS_CONFIRMED']) {
            if ($info['shipping_status'] == $this->config['SS_UNSHIPPED']) {
//                本周主要是根据新的设计图,修改相关接口逻辑
//对商城的前端页面重新进行改写
//目前保证金退还,保证金奖励完成40%

                $info['ostatus'] = '待发货';
                $info['isAfterSale'] = 1;//可操作：申请售后
                if ($info['order_type'] == 2) {//拼团订单
                    if ($info['is_success'] == 0) {
                        $info['ostatus'] = '拼团中';
                    }
                }
                $info['isRefund'] = 1;
            } elseif ($info['shipping_status'] == $this->config['SS_SHIPPED']) {
                $info['ostatus'] = '已发货';
                $info['isAfterSale'] = 1;//可操作：申请售后
                $info['isSign'] = 1;
            } elseif ($info['shipping_status'] == $this->config['SS_SIGN']) {
                $info['ostatus'] = '已完成';
                $shop_after_sale_limit = settings('shop_after_sale_limit');
                if ($shop_after_sale_limit > 0) {//开启售后
                    if ($info['sign_time'] > time() - $shop_after_sale_limit * 86400) {
                        $info['isAfterSale'] = 1;//可操作：申请售后
                    }
                }
            }

            if ($info['is_pay'] > 0 && $info['pay_status'] == $this->config['PS_UNPAYED']) {
                $info['isCancel'] = 1;//可操作：取消
                $info['isPay'] = 1;//可操作：支付
                $info['ostatus'] = '待付款';
            }
        } elseif ($info['order_status'] == $this->config['OS_RETURNED']) {
            $info['ostatus'] = '退货';
        } else {
            if ($info['isDelete'] == 0) {
                if ($info['pay_status'] == 1) {
                    $info['ostatus'] = '取消待退款';
                } else {
                    $info['isDelete'] = 1;
                    $info['ostatus'] = '已取消';
                    if ($info['pay_status'] == 2) {
                        $info['ostatus'] = '已取消，已退款';
                    }
                }
            } else {
                $info['ostatus'] = '已删除';
            }
        }

        if ($info['goodsNum'] == $info['afterSaleNum'] && $info['afterSaleNum'] > 0) {
            $afterSaleOrder = (new AfterSaleModel())->where('order_id', $order_id)->find();

            switch ($afterSaleOrder['status']) {
                case 0:
                    $info['ostatus'] = '售后审核中';
                    break;
                case 1:
                    $info['ostatus'] = '售后审核失败';
                    break;
                case 2:
                    $info['ostatus'] = '待退货';
                    break;
                case 3:
                    $info['ostatus'] = '退货待确认';
                    break;
                case 9:
                    $info['ostatus'] = '已完成';
                    break;
            }
        }

        return $info;
    }
    /*------------------------------------------------------ */
    //-- 获取订单商品
    //-- $order_id int 订单ID
    /*------------------------------------------------------ */
    function orderGoods($order_id, $isSaleAfter = true)
    {
        static $OrderGoodsModel;
        if (empty($OrderGoodsModel)) {
            $OrderGoodsModel = new OrderGoodsModel();
        }
        $rows = $OrderGoodsModel->order('rec_id ASC');
        if (!$isSaleAfter) $rows->where('after_sale_num', 0);
        $rows = $rows->where('order_id', $order_id)->select()->toArray();
        if (empty($rows)) return array();
        $goodsNum = 0;
        $isReview = 0;//能否评论
        $afterSaleNum = 0;//售后商品数量
        foreach ($rows as $key => $row) {
            $row['exp_price'] = explode('.', $row['sale_price']);
            $goodsList[] = $row;
            $goodsNum += $row['goods_number'];
            $afterSaleNum += $row['after_sale_num'];
            if ($row['is_evaluate'] == 1 && $isReview == 0) {
                $isReview = 1;
            }
        }
        return ['goodsList' => $goodsList, 'goodsNum' => $goodsNum, 'isReview' => $isReview, 'afterSaleNum' => $afterSaleNum];
    }

    /*------------------------------------------------------ */
    //-- 写入订单日志
    /*------------------------------------------------------ */
    function _log(&$order, $logInfo = '')
    {
        return OrderLogModel::_log($order, $logInfo);
    }

    /**更新订单信息
     * @param $upData
     * @param string $extType 扩展执行内容
     * @param bool $isTrans 是否启动事务
     * @return bool|string
     */
    function upInfo($upData, $extType = '')
    {
        $order_id = $upData['order_id'];
        $sendMsg = false;
        unset($upData['order_id']);
        $orderInfo = $this->where('order_id', $order_id)->find();
        if (empty($orderInfo)) return '订单不存在.';
        $orderInfo = $orderInfo->toArray();

        $lockWhere = [];    //乐观锁
        $is_admin = true;   //后台管理操作

        if ($extType != 'sys' && defined('AUID') == false) {
            $is_admin = false;
            if ($this->userInfo['user_id'] != $orderInfo['user_id']) {
                return '无权操作';
            }
        }
        if (empty($upData['is_del']) == false && $orderInfo['order_status'] != $this->config['OS_CANCELED']) {
            return '订单未取消不能删除.';
        }
        if ($orderInfo['is_split'] == 2) {
            return '此订单已拆分，不能进行操作.';
        }


        Db::startTrans();//启动事务
        $GoodsModel = new GoodsModel();
        $OrderGoodsModel = new OrderGoodsModel();
        $AccountModel = new AccountModel();
        $time = time();

        if (isset($upData['order_status']) == false) {
            $upData['order_status'] = -1;
        }
        if (isset($upData['pay_status']) == false) {
            $upData['pay_status'] = -1;
        }
        if (isset($upData['shipping_status']) == false) {
            $upData['shipping_status'] = -1;
        }


        if ($upData['order_status'] == $this->config['OS_CONFIRMED']) {//确认订单
            $upData['confirm_time'] = $time;
            if ($orderInfo['order_type'] == 2) {//拼团订单
                (new \app\fightgroup\model\FightGroupListModel)->cleanMemcache($orderInfo['pid']);
            }
        } elseif ($upData['order_status'] == $this->config['OS_CANCELED']) {//取消订单
            $sendMsg = true;
            //非后台操作的订单，只有未取消过的才能取消
            if (!$is_admin) {
                $lockWhere[] = ['cancel_time', 'eq', 0];
            }
            $res = $this->distribution($orderInfo, 'cancel');//提成处理
            if ($res != true) {
                Db::rollback();// 回滚事务
                return '佣金处理失败.';
            }
            //退还订单积分
            if ($orderInfo['use_integral'] > 0) {
                $inData['use_integral'] = $orderInfo['use_integral'];
                $inData['change_type'] = 3;
                $inData['by_id'] = $orderInfo['order_id'];
                $inData['change_desc'] = '订单退还积分:' . $orderInfo['use_integral'];
                $res = $AccountModel->change($inData, $orderInfo['user_id']);
                if ($res != true) {
                    Db::rollback();//回滚
                    return '订单退还积分失败.';
                }
            }//end
            if ($orderInfo['is_stock'] == 1) {//执行商品库存和销量处理
                $orderGoods = $this->orderGoods($order_id);
                if ($orderInfo['order_type'] == 1) {//积分订单
                    $res = (new \app\integral\model\IntegralGoodsListModel)->evalGoodsStore($orderGoods['goodsList'], 'cancel');
                    if ($res != true) {
                        Db::rollback();//回滚
                        return '取消积分订单退库存失败.';
                    }
                } elseif ($orderInfo['order_type'] == 2) {//拼团订单
                    $goods = $orderGoods['goodsList'][0];
                    $res = (new \app\fightgroup\model\FightGoodsModel)->evalGoodsStore($orderInfo['by_id'], $goods['goods_id'], $goods['sku_id'], $goods['goods_number'], 'cancel');
                    if ($res != true) {
                        Db::rollback();//回滚
                        return '取消拼团订单退库存失败.';
                    }
                    if ($orderInfo['is_initiate'] == 1) {//取消团长订单，修改拼团失效时间为当前
                        $res = (new \app\fightgroup\model\FightGroupListModel)->where('gid', $orderInfo['pid'])->update(['fail_time' => time()]);
                        if ($res != true) {
                            Db::rollback();//回滚
                            return '取消拼团订单退库存失败.';
                        }
                    }
                } else {
                    $res = $GoodsModel->evalGoodsStore($orderGoods['goodsList'], 'cancel');
                    if ($res != true) {
                        Db::rollback();//回滚
                        return '取消订单退库存失败.';
                    }
                }
                $upData['is_stock'] = 0;
            }
        } elseif ($upData['pay_status'] === $this->config['PS_UNPAYED']) {//未付款,不执行退款操作，只更新
            $res = $this->distribution($orderInfo, 'unpayed');//提成处理
            if ($res != true) {
                Db::rollback();// 回滚事务
                return '佣金处理失败.';
            }
        } elseif ($upData['pay_status'] == $this->config['PS_RUNPAYED']) {//退款，退回帐户余额
            if ($orderInfo['money_paid'] > 0) {
                $refund_amount = $orderInfo['money_paid'] - $orderInfo['tuikuan_money'];//实付金额减去已退金额
                if (in_array($orderInfo['pay_code'], ['balance', 'offline'])) {//线下打款和余额支付，退回余额
                    $inData['balance_money'] = $refund_amount;
                    $inData['change_type'] = 3;
                    $inData['by_id'] = $orderInfo['order_id'];
                    $inData['change_desc'] = '订单退款到余额:' . $refund_amount;
                    $res = $AccountModel->change($inData, $orderInfo['user_id']);
                    if ($res != true) {
                        Db::rollback();//回滚
                        return '订单退款到余额失败.';
                    }
                } else {//在线退款
                    $code = str_replace('/', '\\', "/payment/" . $orderInfo['pay_code'] . "/" . $orderInfo['pay_code']);
                    $payment = new $code();
                    $orderInfo['refund_amount'] = $refund_amount;//实付金额减去已退金额
                    if ($orderInfo['pid'] > 0 && $orderInfo['order_type'] == 0) {
                        $poWhere[] = ['order_id', '=', $orderInfo['pid']];
                        $poWhere[] = ['is_split', '=', 2];
                        $orderInfo['money_paid'] = $this->where($poWhere)->value('money_paid');
                        $orderInfo['money_paid'] = $orderInfo['money_paid'] * 1;
                    }
                    $res = $payment->refund($orderInfo);
                    if ($res !== true) {
                        Db::rollback();//回滚
                        return '请求退款接口失败：' . $res;
                    }
                }
            }

        } elseif ($upData['shipping_status'] == $this->config['SS_SHIPPED'] && $orderInfo['shipping_status'] == $this->config['SS_UNSHIPPED']) {//发货
            $sendMsg = true;
            $res = $this->distribution($orderInfo, 'shipping');//提成处理
            if ($res != true) {
                Db::rollback();// 回滚事务
                return '佣金处理失败.';
            }
        } elseif ($upData['shipping_status'] === $this->config['SS_UNSHIPPED']) {//未发货
            $res = $this->distribution($orderInfo, 'unshipping');//提成处理
            if ($res !== true) {
                Db::rollback();// 回滚事务
                return '佣金处理失败.';
            }

        } elseif ($upData['shipping_status'] == $this->config['SS_SIGN']) {//签收
            //已发货状态下才能进行签收，二次签收会回滚
            $lockWhere[] = ['shipping_status', 'eq', $this->config['SS_SHIPPED']];
            //积分赠送
            $inData['total_integral'] = $orderInfo['give_integral'];
            $inData['use_integral'] = $inData['total_integral'];
            if ($inData['total_integral'] > 0) {
                $inData['change_type'] = 2;
                $inData['by_id'] = $orderInfo['order_id'];
                $inData['change_desc'] = '签收订单获取积分:' . $orderInfo['order_sn'];
                $res = $AccountModel->change($inData, $orderInfo['user_id']);
                if ($res != true) {
                    Db::rollback();//回滚
                    return '签收赠送积分失败.';
                }
            }
            unset($inData);
            $res = $this->distribution($orderInfo, 'sign');    //提成处理
            if ($res != true) {
                Db::rollback();// 回滚事务
                return '佣金处理失败.';
            }
            //修改订单商品为待评价
            $OrderGoodsModel->where('order_id', $order_id)->update(['is_evaluate' => 1]);
            $shop_after_sale_limit = settings('shop_after_sale_limit');
            $upData['settlement_time'] = $time + $shop_after_sale_limit * 86400;
        } elseif ($upData['order_status'] == $this->config['OS_RETURNED']) {//退货
            $res = $this->distribution($orderInfo, 'returned');//提成处理
            if ($res != true) {
                Db::rollback();// 回滚事务
                return '佣金处理失败.';
            }
            if ($orderInfo['is_evaluate'] == 1) {
                //修改订单商品未评价的设为不需要评价
                $res = $OrderGoodsModel->where('order_id', $order_id)->update(['is_evaluate' => 0]);
                if ($res < 1) {
                    Db::rollback();//回滚
                    return '取消订单商品评价失败.';
                }
            }
        }

        if ($extType == 'changePrice' || $extType == 'editGoods') {//改价或修改商品
            $res = $this->distribution($orderInfo, 'change');//提成处理
            if ($res != true) {
                Db::rollback();// 回滚事务
                return '佣金处理失败.';
            }
        } elseif ($extType == 'unsign') {//撤销签收
            unset($where);
            //查询通过订单获取的积分,扣除
            $where[] = ['by_id', '=', $orderInfo['order_id']];
            $where[] = ['change_type', '=', 2];
            $log = (new AccountLogModel)->where($where)->find();
            if ($log['use_integral'] > 0) {
                unset($inData);
                $inData['total_integral'] = intval($orderInfo['total_amount']) * -1;
                $inData['use_integral'] = $inData['total_integral'];
                $inData['change_type'] = 2;
                $inData['by_id'] = $orderInfo['order_id'];
                if ($extType == 'unsign') {
                    $inData['change_desc'] = '撤销签收退还积分:' . $orderInfo['order_sn'];
                } else {
                    $inData['change_desc'] = '退货退还积分:' . $orderInfo['order_sn'];
                }
                $res = $AccountModel->change($inData, $orderInfo['user_id']);
                if ($res != true) {
                    Db::rollback();//回滚
                    return '退还积分失败.';
                }
            }
            //修改订单商品为不能评价
            $OrderGoodsModel->where('order_id', $order_id)->update(['is_evaluate' => 0]);

            $res = $this->distribution($orderInfo, 'unsign');//提成处理
            if ($res != true) {
                Db::rollback();// 回滚事务
                return '佣金处理失败.';
            }
        } elseif ($extType == 'recover') {//恢复订单
            if ($orderInfo['is_stock'] == 0) {
                $orderGoods = $this->orderGoods($orderInfo['order_id']);
                if ($orderInfo['order_type'] == 1) {//积分订单
                    $res = (new \app\integral\model\IntegralGoodsListModel)->evalGoodsStore($orderGoods['goodsList']);
                } elseif ($orderInfo['order_type'] == 2) {//拼团订单
                    $goods = $orderGoods['goodsList'][0];
                    $res = (new \app\fightgroup\model\FightGoodsModel)->evalGoodsStore($orderInfo['by_id'], $goods['goods_id'], $goods['sku_id'], $goods['goods_number']);
                } else {
                    $res = (new GoodsModel)->evalGoodsStore($orderGoods['goodsList']);
                }
                if ($res !== true) {//扣库存失败，终止
                    Db::rollback();// 回滚事务
                    return '恢复订单，扣库存失败.';
                }
                $upData['is_stock'] = 1;
            }
        }
        //清理未附值定义
        if ($upData['order_status'] == -1) {
            unset($upData['order_status']);
        }
        if ($upData['pay_status'] == -1) {
            unset($upData['pay_status']);
        }
        if ($upData['shipping_status'] == -1) {
            unset($upData['shipping_status']);
        }
        //end


        $upData['update_time'] = $time;
        if (!empty($lockWhere)) {
            $res = $this->where('order_id', $order_id)->where($lockWhere)->update($upData);
        } else {
            $res = $this->where('order_id', $order_id)->update($upData);
        }
        if ($res < 1) {
            Db::rollback();
            return '订单更新失败.';
        }
        Db::commit();// 提交事务

        if ($sendMsg == true) {
            //发送模板消息，给买家
            $WeiXinMsgTplModel = new \app\weixin\model\WeiXinMsgTplModel();
            $WeiXinUsersModel = new \app\weixin\model\WeiXinUsersModel();
            if ($upData['order_status'] == $this->config['OS_CANCELED']) {
                $sendData['send_scene'] = 'order_cancel_msg';//订单取消通知
            } else {
                $sendData['send_scene'] = 'order_shipping_msg';//订单发货通知
                $sendData['shipping_name'] = $upData['shipping_name'];
                $sendData['invoice_no'] = $upData['invoice_no'];
            }
            $sendData['openid'] = $WeiXinUsersModel->where('user_id', $orderInfo['user_id'])->value('wx_openid');
            $sendData['order_id'] = $orderInfo['order_id'];
            $sendData['order_sn'] = $orderInfo['order_sn'];
            $sendData['consignee'] = $orderInfo['consignee'];
            $sendData['order_amount'] = $orderInfo['order_amount'];
            $sendData['add_time'] = $orderInfo['add_time'];
            $WeiXinMsgTplModel->send($sendData);
        }
        $this->cleanMemcache($order_id);
        //第三方接口 执行发货创单
        asynRun('shop/SendLogisticsModel/asynRunLogistics', ['order_id' => $orderInfo['order_id']]);//异步执行
        return true;
    }

    /**
     *发货接口
     */
    public function asynRunLogistics($param)
    {
        if ($param['order_id'] < 1) {
            return '缺少订单ID';
        }
        $param['order_id'] = $param['order_id'] * 1;//异步执行传入必须强制类型
        $orderInfo = $this->find($param['order_id'])->toArray();
        //获取仓库
        $warehouse = Db::name('shop_goods_warehouse')->where(array('id' => $orderInfo['warehouse_id']))->find();
        $shop_logistics_api = Db::name('shop_logistics_api')->where(array('id' => $warehouse['logistics_api']))->find();
        if ($shop_logistics_api) {
            $fun = str_replace('/', '\\', '/app/shop/controller/api/' . $shop_logistics_api['api_file']);
            $kd_api = new $fun();
            $result = $kd_api->sendCreateAdd($param['order_id']);
            if ($result['flag'] == 'success') {
                $status = 1;
            } else {
                $status = 0;

            }
            $insert = array(
                'order_id' => $orderInfo['order_id'],
                'type' => 2,
                'content' => json_encode($result, JSON_UNESCAPED_UNICODE),
                'kd_api_id' => $shop_logistics_api['id'],
                'add_time' => time(),
                'status' => $status,
            );
            logisticsApiLog($insert);
        }
    }


    /**
     * 发货之后查询上级代理商是否有库存,如果有库存扣除代理库存;
     * 代理端:
     * 1.生成提货订单  在下级提货单显示
     * 2.我的库存->出库->增加日志
     */
    public function agentUpGoods($order_id, $type = 0)
    {
        //监测库存是否充足
        if ($type == 1) {
            return $this->agentStock($order_id);
        } else {
            $stockDetailModel = new StockDetailModel();
            $order_where['g.order_id'] = $order_id;
            $order_info = $this->alias('o')->join("shop_order_goods g", 'g.order_id=o.order_id', 'left')
//            ->where($order_where)->field('g.*,o.user_id,o.order_sn,o.transaction_id,o.is_pay,o.pay_id,o.pay_code,o.pay_name,o.consignee,o.province,o.city,o.district,o.merger_name,o.address,o.zipcode,o.tel,o.mobile,o.buyer_message,o.shipping_type,o.shipping_id,o.shipping_name,o.shipping_fee,o.offlineimg,o.money_paid,o.order_amount,o.confirm_time,')->select();
                ->where($order_where)->field('g.rec_id,g.goods_id,g.goods_number,g.brand_id,g.sku_id,g.cid,g.sku_id,g.sku_name,g.sku_val,g.goods_sn,g.goods_name,g.sale_price,g.goods_weight,g.goods_sn,g.pic,g.distribution_amount,o.*')->select();
            Db::startTrans();
            try {

                foreach ($order_info as $k => $v) {
                    $where['user_id'] = $v['user_id'];
                    #获取上级信息
                    $data_info = Db::name('users')->field('pid,user_id')->where($where)->find();
                    if ($data_info['pid'] > 0) {
                        #查询是否是代理商
                        $where_proxy['user_id'] = $data_info['pid'];
                        $proxy_data = Db::name('channel_proxy_users')->where($where_proxy)->find();

                        #查询代理商库存
                        $where_stock['user_id'] = $proxy_data['user_id'];  //代理商id
                        $v['proxy_one_user_id'] = $proxy_data['user_id'];//直属上级代理商id
                        $v['proxy_one_pid'] = $proxy_data['proxy_id'];//当前代理层级ID

                        //查询直属上级代理商id
                        $data_info_pids = Db::name('users')->field('pid,user_id')->where(array('user_id' => $proxy_data['user_id']))->find();
                        if ($data_info_pids['pid'] > 0) {
                            $proxy_data_pids = Db::name('channel_proxy_users')->where(array('user_id' => $data_info_pids['user_id']))->find();
                            $v['proxy_two_user_id'] = $proxy_data_pids['user_id'];//直属上级代理商id
                            $v['proxy_two_pid'] = $proxy_data_pids['proxy_id'];//当前代理层级ID
                        } else {
                            $v['proxy_two_user_id'] = 0;//直属上级代理商id
                            $v['proxy_two_pid'] = 0;//当前代理层级ID
                        }
                        //递归获取上级的上级.....代理商是否有货,没货走平台(修改成跟直属上级拿货)

                        $result_proxy = $this->proxyRecursionExec($where_stock['user_id'], $v['goods_id'], $k, $v);

                        // $send_type 0-由平台发货;1-代理商
                        //如果订单超过24小将由平台发货
                        if ($result_proxy['data']['sku_number'] == 0) {
                            $pay_time = $v['pay_time'];
                            if (strtotime("$pay_time +1day") < time()) {
                                $send_type = 0;
                            } else {
                                $send_type = 1;
                            }
                        } else {
                            $send_type = 1;
                        }

                        if ($result_proxy['type'] == 1 && $send_type == 1) {
                            //上级拿货

                            $v['proxy_user_id'] = $result_proxy['data']['user_id'];  //代理商id
                            $v['proxy_id'] = $result_proxy['data']['proxy_id'];  //当前代理层级ID
                            $v['pid_uid'] = $result_proxy['data']['pid'];  //推荐上级ID
                            //获取推荐上级代理层级
//                            $proxy_users_pid = Db::name('channel_proxy_users')->where(array('user_id' => $proxy_data['pid']))->find();
                            $v['pid_proxy_id'] = $result_proxy['data']['proxy_id']; //当前代理层级ID
                            $proxy_data['user_id'] = $result_proxy['data']['user_id']; //最新代理商id
                            $where_stock['user_id'] = $result_proxy['data']['user_id'];  //最新代理商id
                            $where_stock['goods_id'] = $v['goods_id'];
                            $stock_data = Db::name('channel_proxy_stock')->where($where_stock)->field('id,goods_number')->find();
                            if ($stock_data) {
                                ####代理商有库存
                                #判断库存是否大于购买量
                                if ($stock_data['goods_number'] >= $v['goods_number']) {
                                    #计算需要件减多少代理商库存
//                                $desc_number = $stock_data['goods_number'] - $v['goods_number'];
                                    $desc_number = $v['goods_number'];
                                    $type = 1;
                                } else {
                                    echo "代理库存不足，无法发货1";
                                    die;
                                    #计算需要件减多少代理商库存
                                    $desc_number = $v['goods_number'];
                                    $type = 0;
                                }
                                $desc_update['id'] = $stock_data['id'];
                                #减少库存
                                Db::name('channel_proxy_stock')->where($desc_update)->setDec('goods_number', $desc_number);
                                #增加出货数量
                                Db::name('channel_proxy_stock')->where($desc_update)->setInc('out_number', $desc_number);

                                $_purchase_type = 1;//提货订单，操作云仓库存
                                $operate = 2;//出库
                                $log = '下单提货，扣减库存.';
                                ##############记录日货日志
                                $stockDetailModel->saveLog($proxy_data['user_id'], $_purchase_type, $v['goods_id'], $v['sku_id'], $v['order_id'], $operate, $desc_number, $log, time(), AUID);
                                $this->upOrderGoods($v, $desc_number, $type);

                            }
                        } else {
//                            echo "1111111111111111";
                            //从上级拿货
                        }
                    }
                }

                Db::commit();
//             echo "日志插入成功";
            } catch (\Exception $exception) {
                Db::rollback();
                proxyUpdateLog(array('order_id' => $order_id, 'content' => $exception->getMessage()));
            }
        }
    }


    /**
     * 提货单操作
     * @param $data 订单信息
     * @param $desc_number 商品数量
     * @param  $type 1-全部扣除代理商库存;0-扣除部分
     */
    public function upOrderGoods($data, $desc_number, $type)
    {
        //订单表
        $id = $this->upOrder($data);
        #获取需要给代理商多少钱; 商品总额/减去代理商库存数


        //商品表
        $results = $this->upOrderGoodss($data, $id);

        //增加余额明细
        if ($type == 0) {
            $data['incr_price'] = $data['goods_amount'] / $desc_number;
        } else {
            $data['incr_price'] = $data['goods_amount'];
        }
        $data['shipping_fee_seller'] = $results['shipping_fee_seller'];
        $data['is_shipping_fee_seller'] = $results['is_shipping_fee_seller'];
        $this->proxyUserDetailed($data);
    }

    /**
     * 提货订单插入
     */
    public function upOrder($data)
    {
        $where['order_sn'] = $data['order_sn'];
        $where['user_id'] = $data['proxy_user_id'];
        $data_info = Db::name('channel_order_info')->where($where)->find();
        $channel['order_sn'] = $data['order_sn'];
        $channel['purchase_type'] = 3;#进货类型:1云仓订单,2现货订单3,提货订单
        $channel['user_id'] = $data['proxy_one_user_id'];#代理ID
        $channel['user_proxy_id'] = $data['proxy_one_pid'];#代理层级

        $channel['user_pid'] = $data['proxy_two_user_id'];#代理的推荐上级ID
        $channel['user_pid_proxy_id'] = $data['proxy_two_pid'];#代理推荐上级的层级

        $channel['supply_uid'] = $data['proxy_user_id'];#供货代理ID
        $channel['supply_proxy_id'] = $data['proxy_id'];#供货代理层级

        $channel['order_status'] = 1;#订单状态
        $channel['shipping_status'] = 1;#物流状态
        $channel['pay_status'] = 1;#支付状态
        $channel['transaction_id'] = $data['transaction_id'];#第三方平台交易流水号
        $channel['is_pay'] = $data['is_pay'];#是否需要支付
        $channel['pay_id'] = $data['pay_id'];#支付ID
        $channel['pay_code'] = $data['pay_code'];#支付Code
        $channel['pay_name'] = $data['pay_name'];#支付名称
        $channel['consignee'] = $data['consignee'];#收货人
        $channel['province'] = $data['province'];#省
        $channel['city'] = $data['city'];#市
        $channel['district'] = $data['district'];#区
        $channel['merger_name'] = $data['merger_name'];#省市区
        $channel['address'] = $data['address'];#地址
        $channel['zipcode'] = $data['zipcode'];#邮编
        $channel['mobile'] = $data['mobile'];#mobile
        $channel['buyer_message'] = $data['buyer_message'];#买家留言
        $channel['shipping_type'] = $data['shipping_type'];#用户选择快递
        $channel['shipping_id'] = $data['shipping_id'];#快递ID
        $channel['shipping_name'] = $data['shipping_name'];#快递名称
        $channel['invoice_no'] = $data['invoice_no'];#发货单号
        $channel['goods_amount'] = $data['goods_amount'];#商品总金额
        $channel['shipping_fee'] = $data['shipping_fee'];#运费
        $channel['offlineimg'] = $data['offlineimg'];#线下支付凭证
        $channel['money_paid'] = $data['money_paid'];#已支付金额
        $channel['order_amount'] = $data['order_amount'];#订单金额
        $channel['confirm_time'] = $data['confirm_time'];#确定时间
        $channel['pay_time'] = $data['pay_time'];#支付时间
        $channel['shipping_time'] = time();#发货时间
        $channel['update_time'] = time();#更新时间
        $channel['buy_goods_sn'] = $data['buy_goods_sn'];#购买商品SN
        $channel['buy_goods_id'] = $data['buy_goods_id'];#购买商品SN
        $channel['add_time'] = $data['add_time'];#更新时间
        $channel['update_time'] = time();#更新时间
        $channel['is_phone'] = $data['is_phone'];#是否手机下单
        $channel['ipadderss'] = $data['ipadderss'];#下单IP
        $channel['is_stock'] = 1;#是否执行扣库存,1为已执行
        if ($data_info) {
            Db::name('channel_order_info')->where(array('order_id' => $data_info['order_id']))->update($channel);
            return $data_info['order_id'];
        } else {
            return Db::name('channel_order_info')->insertGetId($channel);

        }

    }

    /**
     * 提货商品订单插入
     */
    public function upOrderGoodss($data, $id)
    {

        $where['order_id'] = $id;
        $where['goods_id'] = $data['goods_id'];
        $data_info = Db::name('channel_order_goods')->where($where)->find();

        $insert['order_id'] = $id;#订单ID
        $insert['brand_id'] = $data['brand_id'];#品牌id


        $insert['cid'] = $data['cid'];#商品分类
        $insert['goods_id'] = $data['goods_id'];#商品ID
        $insert['sku_id'] = $data['sku_id'];#规格ID
        $insert['sku_name'] = $data['sku_name'];#规格名

        $insert['sku_val'] = $data['sku_val'];#规格值
        $insert['goods_sn'] = $data['goods_sn'];#商品货号
        $insert['goods_name'] = $data['goods_name'];#商品名称
        $insert['sale_price'] = $data['sale_price'];#实阶售价
        $insert['goods_weight'] = $data['goods_weight'];#商品重量
        $insert['base_unit'] = 1;#商品基础计量单位ID
        $insert['base_unit_name'] = "件";#商品基础计量单位名
        $insert['goods_unit'] = 1;#商品计量单位ID
        $insert['goods_unit_name'] = "件";#商品计量单位名
        $insert['convert_unit_val'] = 1;#计量单位换算值
        $insert['goods_number'] = $data['goods_number'];#订购数量
        $insert['real_number'] = $data['order_id'];#实际数量=计量单位换算值 * 订购数量
        $insert['pic'] = $data['pic'];#图片
        $insert['add_time'] = time();#time()添加时间
        //卖家出运费
        $result = $this->sellerFreightPrice($data['city'], $data);
        $insert['shipping_fee_seller'] = $result['shipping_fee_seller'];
        $insert['is_shipping_fee_seller'] = $result['is_shipping_fee_seller'];
        if ($data_info) {
            Db::name('channel_order_goods')->where(array('rec_id' => $data_info['rec_id']))->update($insert);
        } else {
            Db::name('channel_order_goods')->insert($insert);

        }
        return $insert;
    }


    /**
     * $region_id 市id
     * 计算卖家运费价格
     */
    public function sellerFreightPrice($param_region_id, $data)
    {
        $shipping_fee_seller = 0;
        $sf_id = array();
        //判断是否开启代理商出运费
        $shipping_fee_plus = settings('shipping_fee_plus_type');//判断是否开启运费
        if ($shipping_fee_plus == 0) {
            return array('shipping_fee_seller' => $shipping_fee_seller, 'is_shipping_fee_seller' => 0);
        }
        //判断该商品运费模板
        $goods_where['goods_id'] = $data['goods_id'];
        $goods_sfid = Db::name('shop_goods')->where($goods_where)->value('freight_template_seller');
        if ($goods_sfid == '-1') {
            $goods_sfid = Db::name('shop_shipping_tpl')->where(array('is_default' => 1))->value('sf_id');
        }
        $sf_id[$goods_sfid] = 0;

        $shipping_fee_plus = settings('shipping_fee_plus');//运费累加计算方式
        $ShippingModel = new \app\shop\model\ShippingModel();
        $shippingList = $ShippingModel->getToSTRows();
        $sfList = array();

        $ShippingTplModel = new \app\shop\model\ShippingTplModel();
        //获取最贵的运费模板，根据起步价判断
        foreach ($sf_id as $key => $val) {
            $ssTpl = $ShippingTplModel->find($key);
            if (empty($ssTpl)) continue;
            $sf_info = json_decode($ssTpl['sf_info'], true);
            if ($shipping_fee_plus == 0) {//不累加运费
                $setSfId = 0;
            } else {
                $setSfId = $ssTpl['sf_id'];
            }

            foreach ($shippingList as $code => $shipping) {
                if ($shipping['status'] == 0 || empty($sf_info[$code])) continue;
                foreach ($sf_info[$code] as $rowb) {
                    $region_id = empty($rowb['region_id']) ? array() : explode(',', $rowb['region_id']);
                    if (empty($rowb['area']) && empty($rowb['region_id'])) continue;//区域定义为空跳出

                    if (empty($rowb['area']) == false) {//如果是全国
                        if (empty($sfList[$setSfId][$code]) == false) {//已有区域定义，跳出
                            continue;
                        }
                        //2301 区id
                    } elseif (in_array($param_region_id, $region_id) == false) {
                        //如果不存在区域，跳出
                        continue;
                    }

                    if (empty($sfList[$setSfId][$code]) == true) {//如果已存在相关运费的模板，按初始运费对比，不论计件或计重
                        if ($sfList[$setSfId][$code]['postage'] > $rowb['postage']) {
                            continue;
                        }
                    }
                    $rowb['sf_id'] = $ssTpl['sf_id'];//快递模板id
                    $rowb['consume'] = $ssTpl['consume'];//消费多少包邮
                    $rowb['sf_name'] = $ssTpl['sf_name']; //模板名称
                    $rowb['valuation'] = $ssTpl['valuation']; //首件几个
                    $sfList[$setSfId][$code] = $rowb;
                }
            }

        }

        foreach ($sfList as $sf) {
            foreach ($sf as $code => $row) {
                #购买数量-首件个数=最新件数
                $d_num = $data['goods_number'] - $row['start'];
                #最新件数/续件个数=最新件数
                $d_num = ceil($d_num / $row['plus']);
                $d_num = $d_num < 0 ? 0 : $d_num;
                #运费+(最新件数*续费价格) =运费
                $shipping_fee_seller = $row['postage'] + ($d_num * $row['postageplus']);

            }
        }
        return array('shipping_fee_seller' => $shipping_fee_seller, 'is_shipping_fee_seller' => 1);

    }

    /**
     * 记录代理商余额明细
     */
    public function proxyUserDetailed($data)
    {
        //判断是否需要给用户分销奖
        $distribution_amount = Db::name('shop_order_goods')->where(array('order_id' => $data['order_id'], 'after_sale_num' => 0, 'return_goods_number' => 0))->sum('distribution_amount');

        $user['order_id'] = $data['order_id'];//订单id
        $user['rec_id'] = $data['rec_id'];//订单id商品
        $user['status'] = 0;//状态:0-冻结;1-到账;3-订单取消
        $user['user_id'] = $data['proxy_user_id'];//代理商id
        $user['shipping_fee'] = $data['shipping_fee_seller'];//代理商付运费金额
        $user['balance_money'] = $data['incr_price'] - $distribution_amount;//帐户余额-调整值
//        $user_in['total_income'] = $data['incr_price'];//累计收入-统计出货
        $user['change_time'] = time();//操作时间
        $user['change_ip'] = request()->ip();//操作时间
        $user['change_desc'] = "出售商品";//操作时间
        $user['change_type'] = 1;//更改类型：1人工调整，2订单相关，3货款相关，4保证金相关，5升级货款，9佣金收入，10提现
        $user['by_id'] = 1;//相关ID，1为后台管理员ID，2为订单ID，3为货款记录ID，4保证金记录ID，9佣金记录ID，10提现记录ID，
        $user['admin_id'] = AUID;//管理员id

        $info = Db::name('users_account_log')->where(array('order_id' => $data['order_id'], 'rec_id' => $data['rec_id'], 'user_id' => $data['proxy_user_id']))->find();

        if (!$info) {

            Db::name('users_account_log')->insertGetId($user);

            //更新卖家运费

//            Db::name('users_account_log')->insert($user);
            #增加用户钱包约
//            Db::name('channel_proxy_users_account')->where(array('user_id' => $user['user_id']))->setInc('balance_money', $user['balance_money']);
            //判断是否需要减去代理商发货金额

            #增加用户冻结钱包
            $user['balance_money'] = $user['balance_money'] - ($data['shipping_fee_seller'] + $data['shipping_fee_seller']);
            Db::name('users_account')->where(array('user_id' => $data['proxy_user_id']))->setInc('frozen_money', $user['balance_money']);

        } else {
            Db::name('users_account_log')->where(array('log_id' => $info['log_id']))->update($user);
        }

        //更新供货商
        $ds_data = array('supplyer_id' => $data['proxy_user_id'], 'is_shipping_fee_seller' => $data['is_shipping_fee_seller'], 'shipping_fee_seller' => $data['shipping_fee_seller']);

        Db::name('shop_order_goods')->where(array('rec_id' => $data['rec_id']))->update($ds_data);


    }


    /**
     * 递归获取上级的上级.....代理商是否有货,没货走平台(修改成只跟上级拿货,上级没有直接跟平台)--监测库存
     */

    public function proxyRecursion($user_id, $goods_id, $for_num = 0, $data_info, $key = 0, $before_uid = 0)
    {

        //查询当前代理商
        $proxy_users_pid = Db::name('channel_proxy_users')->where(array('user_id' => $user_id))->find();
        $where_stock['user_id'] = $user_id;  //代理商id
        $where_stock['goods_id'] = $goods_id;
        if ($proxy_users_pid['proxy_id'] == 0 && $proxy_users_pid['pid'] != 0) {
            return $this->proxyRecursion($proxy_users_pid['pid'], $goods_id, 0, $data_info, $key + 1, $proxy_users_pid['pid']);
        }


        if ($key > 0) {
            if ($proxy_users_pid['pid'] == 0) {
                $proxy_users_pid = Db::name('channel_proxy_users')->where(array('user_id' => $before_uid))->find();

            }
        }
        $stock_data = Db::name('channel_proxy_stock')->where('goods_number', '>=', $data_info['goods_number'])->where($where_stock)->field('id,goods_number')->find();
        if (!$stock_data) {
            if ($proxy_users_pid['proxy_id'] == 0 && $key == 0) {
                return array('type' => 0, 'msg' => "上级不是代理,跟平台拿货", 'data' => $proxy_users_pid);
            } else {

                $proxy_users_pid['pid'] = $proxy_users_pid['user_id'];
                return array('type' => 1, 'msg' => "上级库存不足,提示补货", 'data' => $proxy_users_pid);
            }
        } else {
            return array('type' => 1, 'msg' => "上级拿货", 'data' => $proxy_users_pid);
        }
        /*if (!$stock_data) {
            if ($proxy_users_pid['pid'] == 0) {
                return array('type' => 0, 'msg' => "上级没货,直接跟平台拿货", 'data' => $proxy_users_pid);
            } else {
                return $this->proxyRecursion($proxy_users_pid['pid'], $goods_id);
            }
        } else {
            $this->supplyAgent = $user_id;
            return array('type' => 1, 'msg' => "上级拿货", 'data' => $proxy_users_pid);

        }*/


    }

    /**
     * 减库存
     * @param $user_id
     * @param $goods_id
     * @param int $for_num
     * @param $data_info
     * @param int $key
     * @param int $before_uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function proxyRecursionExec($user_id, $goods_id, $for_num = 0, $data_info, $key = 0, $before_uid = 0)
    {
        //查询当前代理商
        $proxy_users_pid = Db::name('channel_proxy_users')->where(array('user_id' => $user_id))->find();
        $where_stock['user_id'] = $user_id;  //代理商id
        $where_stock['goods_id'] = $goods_id;
        if ($proxy_users_pid['proxy_id'] == 0 && $proxy_users_pid['pid'] != 0) {
            return $this->proxyRecursionExec($proxy_users_pid['pid'], $goods_id, 0, $data_info, $key + 1, $proxy_users_pid['pid']);
        }
        if ($key > 0) {
            if ($proxy_users_pid['pid'] == 0) {
                $proxy_users_pid = Db::name('channel_proxy_users')->where(array('user_id' => $before_uid))->find();

            }
        }
        $stock_data = Db::name('channel_proxy_stock')->where('goods_number', '>=', $data_info['goods_number'])->where($where_stock)->field('id,goods_number')->find();

        if (!$stock_data) {
            if ($proxy_users_pid['proxy_id'] == 0 && $key == 0) {
                $proxy_users_pid['sku_number'] = 0;
                return array('type' => 0, 'msg' => "上级不是代理,跟平台拿货", 'data' => $proxy_users_pid);
            } else {
                $proxy_users_pid['sku_number'] = 0;
                $proxy_users_pid['pid'] = $proxy_users_pid['user_id'];
                return array('type' => 1, 'msg' => "上级库存不足,提示补货", 'data' => $proxy_users_pid);
            }
        } else {
            $proxy_users_pid['sku_number'] = 1;
            return array('type' => 1, 'msg' => "上级拿货", 'data' => $proxy_users_pid);
        }
        /*if (!$stock_data) {
            if ($proxy_users_pid['pid'] == 0) {
                return array('type' => 0, 'msg' => "上级没货,直接跟平台拿货", 'data' => $proxy_users_pid);
            } else {
                return $this->proxyRecursion($proxy_users_pid['pid'], $goods_id);
            }
        } else {
            $this->supplyAgent = $user_id;
            return array('type' => 1, 'msg' => "上级拿货", 'data' => $proxy_users_pid);

        }*/


    }


    /**
     * 通知代理商库存不足去进货
     */
    public function agentStock($order_id)
    {
        $MessageUserModel = new \app\mainadmin\model\MessageUserModel();
        $order_where['g.order_id'] = $order_id;
        $order_info = $this->alias('o')->join("shop_order_goods g", 'g.order_id=o.order_id', 'left')
            ->where($order_where)->field('g.rec_id,g.goods_id,g.goods_number,g.brand_id,g.sku_id,g.cid,g.sku_id,g.sku_name,g.sku_val,g.goods_sn,g.goods_name,g.sale_price,g.goods_weight,g.goods_sn,g.pic,o.*')->select();
        $is_msg = 0;
        foreach ($order_info as $k => $v) {

            $where['user_id'] = $v['user_id'];
            #获取上级信息
            $data_info = Db::name('users')->field('pid,user_id')->where($where)->find();
            if ($data_info['pid'] > 0) {
                //* 递归获取上级的上级.....代理商是否有货,没货走平台(修改成只跟上级拿货,上级没有直接跟平台)
                $res = $this->proxyRecursion($data_info['pid'], $v['goods_id'], $k, $v);
//                var_dump($res);die;
                //获取最新上级信息
                $where_new['user_id'] = $res['data']['user_id'];
                $data_info = Db::name('users')->field('pid,user_id')->where($where_new)->find();
//                $data_info['pid'] = $res['data']['pid'];

                #查询是否是代理商
                $where_proxy['user_id'] = $data_info['user_id'];
                $proxy_data = Db::name('channel_proxy_users')->where($where_proxy)->find();
                if ($proxy_data['proxy_id'] != 0) {

                    //查询代理商库存
                    $where_stock['user_id'] = $proxy_data['user_id'];  //代理商id
                    $where_stock['goods_id'] = $v['goods_id'];
                    $stock_data = Db::name('channel_proxy_stock')->where('goods_number', '>=', $v['goods_number'])->where($where_stock)->field('id,goods_number')->find();
                    $count = Db::name('main_message_user')->where(array('ext_id' => $v['order_id'], 'type' => 4))->count();
                    $pay_time = $v['pay_time'];
                    if (!$stock_data) {
                        $ks[$k] = $stock_data['goods_number'] - $v['goods_number'];
                        if ($ks[$k] < 0) {
                            $diff_num = abs($ks[$k]);
                            if ($count == 0) {
                                if (strtotime("$pay_time +1day") < time()) {
                                    $is_msg = 1;
                                }
                                $MessageUserModel->sendMessage($proxy_data['user_id'], 4, $v['order_id'], '云仓商品库存不足', "下级零售购买，您的《{$v['goods_name']}》库存不足，还缺{$diff_num}件请及时补充库存.【超过24小时该未补货订单将由平台发货】");
                                //发送缺货提醒
                                $sms = new \app\publics\controller\api\Sms();
                                $users = Db::name('users')->where(array('user_id' => $proxy_data['user_id']))->field('mobile')->find();
                                $sms->sendBuhuo($users['mobile'], 1);
                            } else {
                                if (strtotime("$pay_time +1day") < time()) {
                                    $is_msg = 1;
                                }
                            }
                        }
                    }
                }

            }
        }


        if ($is_msg == 1) {
            echo "代理库存不足，无法发货";
            die;
        }

    }

    /**订单后台操作权限
     * @param array $order 订单详情
     * @param bool $by_supplyer 供应商管理
     * @return array
     */
    public function operating(&$order, $by_supplyer = false)
    {
        if ($order['is_split'] == 2) {//已拆分订单主订单不能操作
            return [];
        }
        $os = $order['order_status'];
        $ss = $order['shipping_status'];
        $ps = $order['pay_status'];
        $time = time();
        if ($by_supplyer == true) {
            if ($os == $this->config['OS_CONFIRMED']) { //已确认
                if ($ss == $this->config['SS_UNSHIPPED']) {//未发货
                    $operating['shipping'] = true;
                } elseif ($ss == $this->config['SS_SHIPPED']) {//已发货
                    $operating['sign'] = true;
                    $operating['unshipping'] = true;//设为未发货
                    $operating['returned'] = true;//设为退货
                }
            }
            return $operating;
        }
        if ($os == $this->config['OS_UNCONFIRMED']) {//未确认
            $operating['isCancel'] = true;//取消
            if ($order['pay_id'] == 1) $operating['confirmed'] = true;//确认
            $operating['changePrice'] = true; //改价
            $operating['editConsignee'] = true; //修改收货信息
            $operating['editGoods'] = true; //修改商品
            if ($ps == $this->config['PS_WAITCHACK']) {
                $operating['cfmCodPay'] = true;//设为已付款
            }
        } elseif ($os == $this->config['OS_CONFIRMED']) { //已确认
            if ($ss == $this->config['SS_UNSHIPPED']) {//未发货
                $operating['isCancel'] = true;
                if ($ps == $this->config['PS_UNPAYED']) {//未支付
                    $operating['changePrice'] = true;//改价
                    $operating['editGoods'] = true; //修改商品
                } elseif ($ps == $this->config['PS_PAYED']) {//已支付
                    if ($order['is_pay'] == 2) {
                        $operating['setUnPay'] = true;//设为未付款
                    }
                }
                $operating['shipping'] = true;
                $operating['editConsignee'] = true; //修改收货信息
            } elseif ($ss == $this->config['SS_SHIPPED']) {//已发货
                $operating['sign'] = true;
                $operating['unshipping'] = true;//设为未发货
                $operating['returned'] = true;//设为退货
            } elseif ($ss == $this->config['SS_SIGN']) {//已签收
                if (($order['sign_time'] > $time - 604800)) {
                    //使用售后 $operating['returned'] = true;//设为退货
                    $operating['unsign'] = true;//设为未签收
                }
            } else {
                $operating['isCancel'] = true;
                $operating['changePrice'] = true;
            }
        } elseif ($os == $this->config['OS_RETURNED']) { //已退货
            if ($ps == $this->config['PS_PAYED']) {//退货后可操作退款
                $operating['returnPay'] = true;
            }
        } elseif ($os == $this->config['OS_CANCELED']) { //已关闭
            if ($order['cancel_time'] > $time - 604800) $operating['recover'] = true;//恢复订单
            if ($ps == $this->config['PS_PAYED']) {//取消后可操作退款
                $operating['returnPay'] = true;
            }
        } else {
            $operating['confirmed'] = true;//确认
        }
        return $operating;
    }
    /*------------------------------------------------------ */
    //-- 自动收货
    /*------------------------------------------------------ */
    public function autoSign($uid = 0)
    {
        $where = [];
        $sign_limit = settings('shop_auto_sign_limit');
        $where[] = ['order_status', '=', $this->config['OS_CONFIRMED']];
        $where[] = ['shipping_status', '=', $this->config['SS_SHIPPED']];
        $where[] = ['shipping_time', '<', time() - ($sign_limit * 86400)];
        if ($uid > 0) {
            $where[] = ['user_id', '=', $uid];
        }
        $time = time();
        $order_ids = $this->where($where)->column('order_id');
        foreach ($order_ids as $order_id) {
            $upData['order_id'] = $order_id;
            $upData['shipping_status'] = $this->config['SS_SIGN'];
            $upData['sign_time'] = $time;
            $res = $this->upInfo($upData);
            if ($res === true) {
                $orderInfo = $this->info($order_id);
                $this->_log($orderInfo, '自动签收');
            }
        }
        return true;
    }

    /*------------------------------------------------------ */
    //-- 提成处理&升级处理
    /*------------------------------------------------------ */
    public function distribution(&$orderInfo, $type = '')
    {
        ############分佣信息#########################20210624下单分佣占时不用
        return true;
        if (empty($orderInfo)) return false;
        if ($orderInfo['order_type'] == 1) {//积分商品不返利
            return true;
        }
        if ($orderInfo['is_split'] > 0) {//拆分的主订单不执行
            return true;
        }
        $status = 0;
        if ($orderInfo['shipping_status'] == 1) {//订单已发货
            $status = $this->config['DD_SHIPPED'];
        } elseif ($orderInfo['shipping_status'] == 2) {//订单已签收，重新计算时直接设为已签收待分佣金
            $status = $this->config['DD_SIGN'];
        } elseif ($orderInfo['pay_status'] == 1) {//订单已支付
            $status = $this->config['DD_PAYED'];//    'DD_PAYED' => 1, // 已支付
        }
        $orderInfo['d_type'] = 'order';//普通订单
        $DividendModel = new \app\distribution\model\DividendModel();
        $res = $DividendModel->_eval($orderInfo, $type, $status);
        if ($res !== false && $type == 'add') {
            $buyRes = $DividendModel->buyBrokerageByOrder($orderInfo, $status);
            if ($buyRes === false) {
                return false;
            }
            $res['buy_brokerage_amount'] = $buyRes;
        }
        return $res;
    }
    /*------------------------------------------------------ */
    //-- 提成处理&升级处理
    //-- $orderInfo array
    /*------------------------------------------------------ */
    public function runDistribution(&$orderInfo)
    {
        $mkey = 'runDistribution_' . $orderInfo['order_id'];
        if (redisLook($mkey, 120) == false) {
            return true;
        }
        Db::startTrans();//启动事务
        $upData = $this->distribution($orderInfo, 'add');
        if (is_array($upData) == false) {//扣库存失败，终止
            Db::rollback();// 回滚事务
            return false;
        }
        $upData['is_dividend'] = 1;
        $res = $this->where('order_id', $orderInfo['order_id'])->update($upData);
        if ($res < 1) {
            Db::rollback();// 回滚事务
            return false;
        }
        Db::commit();// 提交事务
        redisLook($mkey, -1);
        return true;
    }

    /*------------------------------------------------------ */
    //-- 订单支付时, 获取订单商品名称
    //-- $order_id int 订单ID
    /*------------------------------------------------------ */
    public function getPayBody($order_id)
    {
        if (empty($order_id)) return "订单ID参数错误";
        $goodsNames = (new OrderGoodsModel)->where('order_id', $order_id)->column('goods_name');
        $gns = implode($goodsNames, ',');
        $payBody = getSubstr($gns, 0, 18);
        return $payBody;
    }
    /*------------------------------------------------------ */
    //-- 拆分订单
    /*------------------------------------------------------ */
    public function splitOrder($order_id)
    {
        static $OrderGoodsModel;
        $orderInfo = $this->find($order_id);
        if (empty($orderInfo)) {
            return false;
        }
        $orderInfo = $orderInfo->toArray();
        if ($orderInfo['is_split'] != 1) {
            return false;
        }
        if (empty($OrderGoodsModel)) {
            $OrderGoodsModel = new OrderGoodsModel();
        }

        $orderGoods = $OrderGoodsModel->order('rec_id ASC')->where('order_id', $orderInfo['order_id'])->select()->toArray();
        $oglist = [];
        $last_supplyer_id = 0;
        foreach ($orderGoods as $og) {
            if (empty($oglist[$og['supplyer_id']])) {
                $oglist[$og['supplyer_id']]['settle_price'] = 0;
                $oglist[$og['supplyer_id']]['goods_amount'] = 0;
                $oglist[$og['supplyer_id']]['discount'] = 0;
                $oglist[$og['supplyer_id']]['goods_sn'] = [];
                $oglist[$og['supplyer_id']]['goods_list'] = [];
            }
            $oglist[$og['supplyer_id']]['give_integral'] += $og['give_integral'] * $og['goods_number'];
            $oglist[$og['supplyer_id']]['use_integral'] += $og['use_integral'] * $og['goods_number'];
            $oglist[$og['supplyer_id']]['settle_price'] += $og['settle_price'] * $og['goods_number'];
            $oglist[$og['supplyer_id']]['goods_amount'] += $og['sale_price'] * $og['goods_number'];
            if ($og['shop_price'] > $og['sale_price']) {
                $oglist[$og['supplyer_id']]['discount'] += ($og['shop_price'] - $og['sale_price']) * $og['goods_number'];
            }
            $oglist[$og['supplyer_id']]['buy_goods_sn'][] = $og['goods_sn'];
            $oglist[$og['supplyer_id']]['goods_ids'][] = $og['goods_id'];
            $oglist[$og['supplyer_id']]['goods_list'][] = $og;
            $last_supplyer_id = $og['supplyer_id'];
        }
        $shipping_fee_detail = json_decode($orderInfo['shipping_fee_detail'], true);
        $i = 1;
        $use_bonus = $orderInfo['use_bonus'];
        $shipping_fee = $orderInfo['shipping_fee'];
        $diy_discount = $orderInfo['diy_discount'];
        foreach ($oglist as $key => $sogl) {
            $inArr = $orderInfo;
            unset($inArr['order_id']);
            $inArr['order_sn'] .= '-' . $i;
            $inArr['is_split'] = 0;
            $inArr['supplyer_id'] = $key;
            $inArr['give_integral'] = $sogl['give_integral'];
            $inArr['use_integral'] = $sogl['use_integral'];
            $inArr['pid'] = $orderInfo['order_id'];
            $inArr['buy_goods_sn'] = join(',', $sogl['buy_goods_sn']);
            $inArr['buy_goods_id'] = join(',', $sogl['goods_ids']);
            $inArr['discount'] = $sogl['discount'];
            $inArr['goods_amount'] = $sogl['goods_amount'];
            //使用相关优惠处理
            $scale = $sogl['goods_amount'] / $orderInfo['goods_amount'];//对比总订单商品价格占比
            $inArr['use_bonus'] = 0;
            if ($orderInfo['use_bonus'] > 0) {
                if ($last_supplyer_id == $key) {
                    $inArr['use_bonus'] = $use_bonus;
                } else {
                    $inArr['use_bonus'] = bcmul($orderInfo['use_bonus'], $scale, 2);
                    $use_bonus -= $inArr['use_bonus'];
                }

            }
            $inArr['shipping_fee'] = 0;
            if ($orderInfo['shipping_fee'] > 0) {
                if (empty($shipping_fee_detail[$key]) == false) {
                    $inArr['shipping_fee'] = $shipping_fee_detail[$key];
                } else {
                    if ($last_supplyer_id == $key) {
                        $inArr['shipping_fee'] = $shipping_fee;
                    } else {
                        $inArr['shipping_fee'] = bcmul($orderInfo['shipping_fee'], $scale, 2);
                        $shipping_fee -= $inArr['shipping_fee'];
                    }

                }
            }
            $inArr['settle_goods_price'] = $sogl['settle_price'];
            $inArr['settle_price'] = $sogl['settle_price'];
            $inArr['diy_discount'] = 0;
            if ($orderInfo['diy_discount'] > 0) {
                if ($last_supplyer_id == $key) {
                    $inArr['diy_discount'] = $diy_discount;
                } else {
                    $inArr['diy_discount'] = bcmul($orderInfo['diy_discount'], $scale, 2);
                    $diy_discount -= $inArr['diy_discount'];
                }
                // $inArr['diy_discount'] = bcmul($orderInfo['diy_discount'], $scale, 2);
            }
            $inArr['order_amount'] = $inArr['goods_amount'] - $inArr['use_bonus'] - $inArr['diy_discount'] + $inArr['shipping_fee'];
            $inArr['money_paid'] = $inArr['order_amount'];
            //end
            $res = $this->create($inArr);
            $order_id = $res->order_id;
            if ($order_id < 1) return false;
            foreach ($sogl['goods_list'] as $goods) {
                $goods['order_id'] = $order_id;
                unset($goods['rec_id']);
                $res = $OrderGoodsModel->create($goods);
                if ($res->rec_id < 1) return false;
            }
            $inArr['order_id'] = $order_id;
            $this->info($order_id);
            $this->_log($inArr, '订单拆分：' . $orderInfo['order_sn'] . '，拆分生成子订单');
            $i++;
        }

        return true;
    }
    /*------------------------------------------------------ */
    //-- 订单支付成功处理
    /*------------------------------------------------------ */
    public function updatePay($upData = [], $_log = '支付成功')
    {

        $orderInfo = $this->find($upData['order_id'])->toArray();
        unset($upData['order_amount']);
        //'PS_PAYED' => 1, // 已付款
        $upData['pay_status'] = $this->config['PS_PAYED'];

        if ($orderInfo['pay_status'] == 0) {
            //'OS_CONFIRMED' => 1,// 已确认
            $upData['order_status'] = $this->config['OS_CONFIRMED'];
            $upData['is_pay_eval'] = 1;//设为待执行支付成功后的相关处理
        }
        $orderInfo['pay_status'] = $upData['pay_status'];
        $upData['pay_time'] = time();
        $res = $this->upInfo($upData, 'sys');
        if ($res !== true) {
            return false;
        }
        $this->_log($orderInfo, $_log);

        //异步有几率会出问题(导致不执行)
        asynRun('shop/OrderModel/asynRunPaySuccessEval', ['order_id' => $upData['order_id']]);//异步执行
//        $this->asynRunPaySuccessEval(['order_id' => $upData['order_id']]);
        return true;
    }
    /*------------------------------------------------------ */
    //-- 支付成功后执行(异步执行)
    //-- $param array 必须带有order_id
    /*------------------------------------------------------ */
    public function asynRunPaySuccessEval($param)
    {


        if ($param['order_id'] < 1) {
            return '缺少订单ID';
        }
        $mkey = 'paySuccessEvalIng' . $param['order_id'];
        if (redisLook($mkey, 30) == false) {
//            return true;
        }
        $param['order_id'] = $param['order_id'] * 1;//异步执行传入必须强制类型
        $orderInfo = $this->find($param['order_id'])->toArray();
        if ($orderInfo['is_pay_eval'] != 1) {
//            return true;
        }
        //执行库存扣除，下单时未扣库存，则支付成功后扣除
        $orderGoods = $this->orderGoods($orderInfo['order_id']);

        //先扣库存才能拆分订单，拆分订单时不扣库存
        if ($orderInfo['is_stock'] == 0) {
            Db::startTrans();//启动事务
            if ($orderInfo['order_type'] == 1) {//积分订单
                $res = (new \app\integral\model\IntegralGoodsListModel)->evalGoodsStore($orderGoods['goodsList']);
            } else {
                $res = (new GoodsModel)->evalGoodsStore($orderGoods['goodsList']);
            }
            if ($res !== true) {//扣库存失败，终止
                Db::rollback();// 回滚事务
                $this->_log($orderInfo, '扣库存失败');
                return '扣库存失败';
            }
            $upData['is_stock'] = 1;
            $res = $this->where('order_id', $orderInfo['order_id'])->update($upData);
            if ($res < 1) {
                Db::rollback();// 回滚事务
                $this->_log($orderInfo, '扣库存失败');
                return '扣库存更新订单状态失败';
            }
            Db::commit();// 提交事务
            $orderInfo['is_stock'] = 1;
        }//end

        $UsersModel = new \app\member\model\UsersModel();
        $usersInfo = $UsersModel->info($orderInfo['user_id']);//获取会员信息
        //更新会员最后购买时间&累计消费
        if ($usersInfo['last_buy_time'] < $orderInfo['add_time']) {
            $UsersModel->upInfo($orderInfo['user_id'], ['last_buy_time' => $orderInfo['add_time'], 'total_consume' => ['INC', $orderInfo['order_amount']]]);
        }

        //如果设置支付再绑定关系时执行
        if (settings('bind_pid_time') == 1 && $usersInfo['is_bind'] == 0) {//支付成功时绑定关系
            $UsersModel->regUserBind($orderInfo['user_id'], -1);
        }//end

        //确认订单，执行拆单处理，独立出来并外部使用事务
        if ($orderInfo['is_split'] == 1) {
            Db::startTrans();//启动事务
            $res = $this->splitOrder($orderInfo['order_id']);
            if ($res == true) {
                $upData['is_split'] = 2;
                $res = $this->where('order_id', $orderInfo['order_id'])->update($upData);
                if ($res > 0) {
                    $this->_log($orderInfo, '拆分订单');
                    Db::commit();// 提交事务
                    return true;//订单被拆分后，终止，不执行下面的处理
                }
            }
            Db::rollback();// 回滚事务
        }//end

        Db::startTrans();//启动事务
        if ($orderInfo['is_dividend'] == 0) {
            //############分佣信息#########################20210624下单分佣占时不用
            /* $upData = $this->distribution($orderInfo, 'add', $this->config['DD_PAYED']);//提成处理
             if (is_array($upData) == false) {
                 Db::rollback();// 回滚事务
                 $this->_log($orderInfo, '佣金处理失败-1.');
                 return '佣金处理失败-1.';
             }*/
        } else {
            $res = $this->distribution($orderInfo, 'pay');//提成处理
            if ($res == false) {
                Db::rollback();// 回滚事务
                $this->_log($orderInfo, '佣金处理失败-2.');
                return '佣金处理失败-2.';
            }
        }

        Db::commit();// 提交事务


        // 佣金--暂时不用
        //$upData['dividend_amount'] = $this->disposeCommission($orderInfo, $orderGoods['goodsList']);
        $upData['dividend_amount'] = 0;
        $upData['is_pay_eval'] = 2;
        $this->where('order_id', $orderInfo['order_id'])->update($upData);
        $this->cleanMemcache($orderInfo['order_id']);

        //扣库存
        //商城订单无需扣库存  order_types  0-商城订单;1-代理商订单

        if ($orderInfo['order_types'] == 1) {
            $this->deductStock($orderInfo, $orderGoods['goodsList']);
        }
        /*------------------------------------------------------ */
        //-- 拆单(根据不同仓库)
        /*------------------------------------------------------ */
        $this->warehouseSplit($param['order_id']);

        //升级处理
        $DividendModel = new \distribution\base\Dividend();
        $DividendModel->evalLevelUp($orderInfo);//升级处理
        //发送短息提醒
        $sms = new \app\publics\controller\api\Sms();
        $sms->sendBuhuo($orderInfo['mobile'], 2);
        return true;
    }




    /*------------------------------------------------------ */
    //-- 判断是否需要给上次分销(只有上级不是代理商才会分销)
    /*------------------------------------------------------ */
    public function superiorDistribution($order_id)
    {

        $UsersModel = new UsersModel();
        $ProxyUsersModel = new ProxyUsersModel();
        $AccountModel = new AccountModel();
        $DividendModel = new DividendModel();


        $shop_order_info = Db::name('shop_order_info')->where(array('order_id' => $order_id))->find();

        $user = Db::name('users')->where(array('user_id' => $shop_order_info['user_id']))->find();
        // 上级
        $p_user = $UsersModel->info($user['pid']);

        // 代理端
        $c_p_user = $ProxyUsersModel->info($user['pid']);

        //不是代理才执行分销
        if ($c_p_user['proxy_id'] == 0) {

            $p_role_id = $p_user['role_id'];
            $role_name = $p_user['role']['role_name'];

            if ($shop_order_info) {

                $count = Db::name('distribution_dividend_log')->where(array('buy_uid' => $shop_order_info['user_id']))->count();

                //分销金额
                $distribution_price = 0;
                $shop_order_goods = Db::name('shop_order_goods')->where(array('order_id' => $shop_order_info['order_id']))->select();
                foreach ($shop_order_goods as $k => $v) {
                    //查询vip分销比例
                    $shop_goods = Db::name('shop_goods')->where(array('goods_id' => $v['goods_id']))->field('recommend_award')->find();
                    $recommend_award = json_decode($shop_goods['recommend_award'], true);
                    //分享比例
                    if (isset($recommend_award['7'])) {
                        if ($recommend_award['7'] != '' && $recommend_award['7'] > 0) {
                            //按比例计算
                            /* $ratio = $recommend_award['7'] / 100;;
                            $dis_price = ($v['sale_price'] * $v['goods_number']) * $ratio;*/
                            //固定金额计算
                            //更新分销金额
                            $dis_price = $v['goods_number'] * $recommend_award['7'];
                            if ($count == 0) {
                                Db::name('shop_order_goods')->where(array('rec_id' => $v['rec_id']))->update(array('distribution_amount' => $dis_price, 'update_time' => time()));
                            }
                            #当前商品的分享金额
                            $distribution_price += $dis_price;
                        }
                    }
                }
                if ($distribution_price > 0) {
                    if ($count == 0) {

                        $p_award = sprintf("%.2f", $distribution_price);
                        $ins_arr[] = $this->dividendLog($shop_order_info, $p_award, $p_user, $p_role_id, $role_name, '分销奖', true);
                        $DividendModel->insertAll($ins_arr);
                    }
                    // 直接打款(改成确认收货待打款)
                    /*  $AccountModel->change([
                          'total_dividend' => $p_award,
                          'balance_money' => $p_award,
                          'change_type' => 4,
                          'change_desc' => '分销奖',
                          'by_id' => $order_id
                      ], $user['pid']);*/
                }

//                echo "执行成功";

            }
        }


    }

    /*------------------------------------------------------ */
    //-- 拆单(根据不同仓库)
    /*------------------------------------------------------ */
    public function warehouseSplit($order_id)
    {
        Db::startTrans();
        try {
            //获取订单
            $shop_order_info = Db::name('shop_order_info')->where(array('order_id' => $order_id))->find();
            $pid_order_id = $shop_order_info['order_id'];

            $order_sn = $shop_order_info['order_sn'];
            $old_order_id = $shop_order_info['order_id'];
            $use_integral = $shop_order_info['use_integral'];

            //获取订单商品表
            $shop_order_goods = Db::name('shop_order_goods')->where(array('order_id' => $order_id))->group('warehouse_id')->select();

            $where[] = ['is_credit_amount', '=', 1];
            $where[] = ['goods_id', 'in', $shop_order_info['buy_goods_id']];
            $shop_goods = Db::name('shop_goods')->where($where)->field('goods_id')->select();
            $result = array_column($shop_goods, 'goods_id');

            #可使用积分商品的总额
            $total_price = 0;

            //判断是否需要拆单
            if (count($shop_order_goods) > 1) {
                //执行拆单
                foreach ($shop_order_goods as $k => $v) {
                    #判断商品是否可用积分
                    if (!in_array($v['goods_id'], $result)) {
                        unset($shop_order_info['use_integral']);
                    } else {
                        $total_price += $v['goods_number'] * $v['sale_price'];
                    }
                    if ($v['discount'] == 0) {
                        unset($shop_order_info['discount']);
                    }
                    unset($shop_order_info['order_id']);
                    $shop_order_info['is_split'] = 1;
                    $shop_order_info['pid'] = $old_order_id;
                    $shop_order_info['order_sn'] = $order_sn . '_' . $k;
                    $shop_order_info['warehouse_id'] = $v['warehouse_id'];
                    //商品总额
                    $shop_order_info['goods_amount'] = $v['goods_number'] * $v['sale_price'];
                    //折扣金额
                    $shop_order_info['discount'] = $v['discount'];
                    $shop_order_info['money_paid'] = $shop_order_info['goods_amount'];
                    $shop_order_info['order_amount'] = $shop_order_info['goods_amount'];
                    $new_id = Db::name('shop_order_info')->insertGetId($shop_order_info);
                    if ($new_id) {
                        //更新关联订单
                        Db::name('shop_order_goods')->where(array('rec_id' => $v['rec_id']))->update(array('order_id' => $new_id));
                        //判断是否需要给上次分销(只有上级不是代理商才会分销)
                        $this->superiorDistribution($shop_order_info['order_id']);
                    }
                }
                //更新主订单为隐藏
                Db::name('shop_order_info')->where(array('order_id' => $pid_order_id))->update(array('is_status' => 0));
            } else {
                //判断是否需要给上次分销(只有上级不是代理商才会分销)
                $this->superiorDistribution($shop_order_info['order_id']);
                Db::name('shop_order_info')->where(array('order_id' => $shop_order_info['order_id']))->update(array('warehouse_id' => $shop_order_goods[0]['warehouse_id']));
            }

            #######################################平分积分###############################################################333
            $setting = settings();
            if ($use_integral > 0) {

                $wheres[] = ['pid', '=', $old_order_id];
                $wheres[] = ['use_integral', '>', 0];
                $run_order_info = Db::name('shop_order_info')->where($wheres)->select();

                foreach ($run_order_info as $k => $v) {

                    //获得这个商品可以使用多少积分
                    $order_use_integral = round(($v['order_amount'] / $total_price) * $use_integral, 2);

                    //获取积分配置
                    $setting_integral = json_decode($setting['system_setting'], true)['integral_value'];
                    //积分价值多少钱
                    $integral_price = $order_use_integral / $setting_integral;
                    //更新订单
                    Db::name('shop_order_info')->where(array('order_id' => $v['order_id']))->setDec('money_paid', $integral_price);
                    Db::name('shop_order_info')->where(array('order_id' => $v['order_id']))->setDec('order_amount', $integral_price);
                    Db::name('shop_order_info')->where(array('order_id' => $v['order_id']))->update(array('use_integral' => $order_use_integral));
                }
            }
            #######################################平分积分###############################################################333
            Db::commit();
        } catch (\Exception $msg) {
            Db::rollback();
        }


    }

    public function disposeCommission($orderInfo, $goodsList)
    {
        $GoodsModel = new GoodsModel();
        $ChannelGoodsModel = new ChannelGoodsModel();
        $OrderGoodsModel = new OrderGoodsModel();
        $AccountModel = new AccountModel();
        $DividendModel = new DividendModel();
        $UsersModel = new UsersModel();
        $ProxyUsersModel = new ProxyUsersModel();
        $RegionModel = new ProxyUserRegionModel();
        $ProxyLevelModel = new ProxyLevelModel();
        $RewardModel = new RewardModel();
        // 用户
        $user = $UsersModel->info($orderInfo['user_id']);

        // 代理端
        $c_user = $ProxyUsersModel->info($orderInfo['user_id']);
        if ($c_user['proxy_id'] > 0) {
            $role_id = $c_user['proxy_id'];
        } else {
            $role_id = $user['role_id'];
        }
        // 积分赠送
        $u_award = 0;
        // 云仓商品
        $channel_goods = $ChannelGoodsModel->where('isputaway', 1)->column('goods_id');
        // 订单商品
        $order_goods = $OrderGoodsModel->where('order_id', $orderInfo['order_id'])->select()->toArray();
        // 上级
        $p_user = $UsersModel->info($user['pid']);
        // 代理端
        $c_p_user = $ProxyUsersModel->info($user['pid']);
        if ($c_p_user['proxy_id'] > 0) {
            $p_role_id = $c_p_user['proxy_id'];
            $role_name = $c_p_user['proxyLevel']['proxy_name'];
        } else {
            $p_role_id = $p_user['role_id'];
            $role_name = $p_user['role']['role_name'];
        }
        // 一级分销
        $p_award = 0.00;
        // 佣金总额
        $dividend_amount = 0;
        $channel = true;
        // 处理
        foreach ($order_goods as $val) {
            // 商品信息
            $goods = $GoodsModel->info($val['goods_id']);
            // 普通商品分销
            if (in_array($val['goods_id'], $channel_goods) == false) { // 普通商品
                // 分销奖
                if ($goods['recommend_award'][$p_role_id] > 0) {
                    $p_award += $val['sale_price'] * $val['goods_number'] * $goods['recommend_award'][$p_role_id] / 100;
                }
                $channel = false;
            } else { // 云仓商品
                // 积分赠送
                if ($goods['integral_award'][$role_id] > 0) {
                    $u_award += $goods['integral_award'][$role_id] * $val['goods_number'];
                }
            }
        }
        // 佣金日志
        $ins_arr = array();
        // 区代
        $district = $RegionModel->where('region_id', $orderInfo['district'])->find();
        // 市代
        $city = $RegionModel->where('region_id', $orderInfo['city'])->find();
        // 省代
        $province = $RegionModel->where('region_id', $orderInfo['province'])->find();
        // 国代
        $max = $ProxyLevelModel->order('level', 'asc')->value('proxy_id');
        $country = $ProxyUsersModel->findCountry($user['pid'], $max);
        // 区域奖励
        $reward_type = $RewardModel->where('reward_type', 'qyj')->value('info');
        $reward_type = json_decode($reward_type, true);
        // 区域奖
        if (empty($district) == false) { // 区代
            $district_award = sprintf('%.2f', $orderInfo['order_amount'] * $reward_type['district'] / 100);
            $district_user = $ProxyUsersModel->info($district['user_id']);
            $ins_arr[] = $this->dividendLog($orderInfo, $district_award, $district_user, $district_user['proxy_id'],
                $district_user['proxyLevel']['proxy_name'], '区域奖(区代)', $channel);
            /*$AccountModel->change([
                'total_dividend' => $district_award,
                'balance_money' => $district_award,
                'change_type' => 4,
                'change_desc' => '区域奖(区代)',
                'by_id' => $orderInfo['order_id']
            ], $district_user['user_id']);*/
            $dividend_amount += $district_award;
        }
        if (empty($city) == false) { // 市代
            $city_award = sprintf('%.2f', $orderInfo['order_amount'] * $reward_type['city'] / 100);
            $city_user = $ProxyUsersModel->info($city['user_id']);
            $ins_arr[] = $this->dividendLog($orderInfo, $city_award, $city_user, $city_user['proxy_id'],
                $city_user['proxyLevel']['proxy_name'], '区域奖(市代)', $channel);
            /*$AccountModel->change([
                'total_dividend' => $city_award,
                'balance_money' => $city_award,
                'change_type' => 4,
                'change_desc' => '区域奖(市代)',
                'by_id' => $orderInfo['order_id']
            ], $city_user['user_id']);*/
            $dividend_amount += $city_award;
        }
        if (empty($province) == false) { // 省代
            $province_award = sprintf('%.2f', $orderInfo['order_amount'] * $reward_type['province'] / 100);
            $province_user = $ProxyUsersModel->info($province['user_id']);
            $ins_arr[] = $this->dividendLog($orderInfo, $province_award, $province_user, $province_user['proxy_id'],
                $province_user['proxyLevel']['proxy_name'], '区域奖(省代)', $channel);
            /*$AccountModel->change([
                'total_dividend' => $province_award,
                'balance_money' => $province_award,
                'change_type' => 4,
                'change_desc' => '区域奖(省代)',
                'by_id' => $orderInfo['order_id']
            ], $province_user['user_id']);*/
            $dividend_amount += $province_award;
        }
        if ($country > 0) { // 国代
            $country_award = sprintf('%.2f', $orderInfo['order_amount'] * $reward_type['country'] / 100);
            $country_user = $ProxyUsersModel->info($country);
            $ins_arr[] = $this->dividendLog($orderInfo, $country_award, $country_user, $country_user['proxy_id'],
                $country_user['proxyLevel']['proxy_name'], '区域奖(国代)', $channel);
            /*$AccountModel->change([
                'total_dividend' => $country_award,
                'balance_money' => $country_award,
                'change_type' => 4,
                'change_desc' => '区域奖(国代)',
                'by_id' => $orderInfo['order_id']
            ], $country_user['user_id']);*/
            $dividend_amount += $country_award;
        }
        if ($u_award > 0) { // 积分赠送
            $AccountModel->change([
                'total_integral' => $u_award,
                'use_integral' => $u_award,
                'change_type' => 2,
                'change_desc' => '购买赠送',
                'by_id' => $orderInfo['order_id']
            ], $user['user_id']);
        }
        if ($p_award > 0) { // 分销奖
            $p_award = sprintf("%.2f", $p_award);
            $ins_arr[] = $this->dividendLog($orderInfo, $p_award, $p_user, $p_role_id, $role_name, '分销奖', $channel);
            // 直接打款
            /*$AccountModel->change([
                'total_dividend' => $p_award,
                'balance_money' => $p_award,
                'change_type' => 4,
                'change_desc' => '分销奖',
                'by_id' => $orderInfo['order_id']
            ], $user['pid']);*/
            $dividend_amount += $p_award;
        }
        if (empty($ins_arr) == false) {
            $DividendModel->insertAll($ins_arr);
        }
        return $dividend_amount;
    }

    public function dividendLog($orderInfo, $award, $user, $role_id, $role_name, $title, $channel = false)
    {
        #0-	订单待确定 ;1-订单已支付;2-订单已发货;3-已签收,待分成;9-已到账
        $status = 1;
        if ($channel == false) {
            $status = $orderInfo['order_status'];
        }
        $data = [
            'status' => $status,
            'order_type' => 'order',
            'order_id' => $orderInfo['order_id'],
            'order_sn' => $orderInfo['order_sn'],
            'buy_uid' => $orderInfo['user_id'],
            'order_amount' => $orderInfo['order_amount'],
            'dividend_amount' => $award,
            'dividend_uid' => $user['user_id'],
            'role_id' => $role_id['role_id'],
            'role_name' => $role_name,
            'level_award_name' => $title,
            'add_time' => time(),
            'update_time' => time(),
        ];
        return $data;
    }

    /**
     * 扣库存
     */
    public function deductStock($orderInfo, $goodsList)
    {
        $proxyUserModel = new ProxyUsersModel();
        $proxyUserInfo = $proxyUserModel->info($orderInfo['user_id']);
        $stockModel = new StockModel();
        $stockDetailModel = new StockDetailModel();
        $MessageUserModel = new \app\mainadmin\model\MessageUserModel();
        $ProxyAccountModel = new WalletModel();
        $GoodsPrice = new GoodsPricesModel();
        $GoodsModel = new GoodsModel();
        $ChannelGoodsModel = new ChannelGoodsModel();
        $AccountModel = new AccountModel();
        $DividendModel = new DividendModel();
        $logArr = [];
        $ProxyLevelList = (new ProxyLevelModel)->getList();
        // 级差用户
        $range_user = $this->findLevel($proxyUserInfo, $proxyUserInfo['pid']);
        // 级差奖励
        $range_award = 0.00;

        foreach ($goodsList as $goods) {
            // 云仓商品
            $isChannelGoods = ChannelGoodsModel::where('goods_id', $goods['goods_id'])->find();
            if (empty($isChannelGoods)) continue;

            // 是否发现
            $is_find = false;
            // 拿货上级
            $supply_uid = $proxyUserModel->getSupplyUid($proxyUserInfo['user_id'], $proxyUserInfo['proxy_id'], $ProxyLevelList);
            $proxySupplyUserInfo = $proxyUserModel->info($supply_uid);
            do {
                if (empty($proxySupplyUserInfo)) break;
                // 货款
                $goods_money = $goods['goods_number'] * $goods['sale_price'];
                // 商品数量
                $goods_number = $stockModel->where('user_id', $proxySupplyUserInfo['user_id'])
                    ->where('goods_id', $goods['goods_id'])
                    ->where('sku_id', $goods['sku_id'])
                    ->value('goods_number') ?: 0;
                //库存扣库存
                if ($goods_number >= $goods['goods_number']) {
                    $is_find = true;
                    $hash_code = md5($proxySupplyUserInfo['user_id'] . '_' . 1 . '_' . $goods['goods_id'] . '_' . $goods['sku_id']);
                    $where = [];
                    $where[] = ['user_id', '=', $proxySupplyUserInfo['user_id']];
                    $where[] = ['hash_code', '=', $hash_code];
                    $stockModel->where($where)->update([
                        'goods_number' => ['DEC', $goods['goods_number']],
                        'out_number' => ['INC', $goods['goods_number']],
                        'update_time' => time()
                    ]);
                    //记录
                    $stockDetailModel->saveLog($proxySupplyUserInfo['user_id'], 1, $goods['goods_id'], $goods['sku_id'],
                        $orderInfo['order_id'], 2, $goods['goods_number'], '下级' . $orderInfo['user_id'] . '零售购买，扣减库存', time(), 0);
                    // 货款
                    $logArr[$proxySupplyUserInfo['user_id']] += $goods_money;
                } else {
                    //库存不足 则找下个代理重新判断
                    //发送站内信
                    $diff_num = $goods['goods_number'] - $goods_number;
                    $MessageUserModel->sendMessage($proxySupplyUserInfo['user_id'], 3, $orderInfo['order_id'], '云仓商品库存不足', "下级零售购买，您的《{$goods['goods_name']}》库存不足，还缺{$diff_num}件请及时补充库存.");
                    $supply_uid = $proxyUserModel->getSupplyUid($proxySupplyUserInfo['user_id'], $proxySupplyUserInfo['proxy_id'], $ProxyLevelList);
                    $proxySupplyUserInfo = $proxyUserModel->info($supply_uid);
                }
            } while ($is_find == false);
            $range = 0;
            if ($range_user['user_id'] > 0 && $proxySupplyUserInfo['user_id'] != $range_user['user_id']) {
                if ($range_user['channel'] == 0) { // 普通身份
                    // $goods_price = $GoodsModel->purchaseGoodsInfo($goods['goods_id'], $range_user['role_id']);
                    $goods_info = $GoodsModel->info($goods['goods_id']);
                    if ($goods_info['role_price_type'] > 0) { // 有阶梯价格
                        // 商品价格
                        $goods_price_list = $GoodsPrice->where('goods_id', $goods['goods_id'])
                            ->where('type', 'role')->column('price', 'by_id');
                        if ($goods_info['role_price_type'] == 1) { // 指定折扣售价
                            $goods_price = $goods_info['shop_price'] * $goods_price_list[$range_user['role_id']] / 100;
                        } else { // 指定固定售价
                            $goods_price = $goods_price_list[$range_user['role_id']];
                        }
                    }
                } else { // 代理身份
                    $goods_price = $ChannelGoodsModel->purchaseGoodsInfo($goods['goods_id'], $range_user['role_id']);
                }
                $range = ($goods['sale_price'] - $goods_price) * $goods['goods_number'];
                $range_award += $range;
                $logArr[$proxySupplyUserInfo['user_id']] -= $range;
            }
        }

        // 发放货款
        if (!empty($logArr)) {
            foreach ($logArr as $key => $val) {
                $ProxyAccountModel->change([
                    'balance_money' => $val,
                    'total_income' => $val,
                    'change_desc' => '出售商品',
                    'change_type' => 12,
                    'by_id' => $orderInfo['order_id']
                ], $key);
            }
        }
        if ($range_award > 0) { // 差价奖
            $range_award = sprintf('%.2f', $range_award);
            // 打款
            $AccountModel->change([
                'balance_money' => $range_award,
                'total_income' => $range_award,
                'change_desc' => '差价奖',
                'change_type' => 4,
                'by_id' => $orderInfo['order_id']
            ], $range_user['user_id']);
            // 添加记录
            $data = [
                'status' => 9,
                'order_type' => 'order',
                'order_id' => $orderInfo['order_id'],
                'order_sn' => $orderInfo['order_sn'],
                'buy_uid' => $orderInfo['user_id'],
                'order_amount' => $orderInfo['order_amount'],
                'dividend_amount' => $range_award,
                'dividend_uid' => $range_user['user_id'],
                'role_id' => $range_user['role_id'],
                'role_name' => $range_user['role_name'],
                'level_award_name' => '差价奖',
                'add_time' => time(),
                'update_time' => time(),
            ];
            $DividendModel->insert($data);
        }
    }

    public function findLevel($user, $pid, $time = 0)
    {
        if ($time > 50) return ['user_id' => 0];
        $time++;
        if ($pid < 1) return ['user_id' => 0];
        $UsersModel = new UsersModel();
        $ProxyUsersModel = new ProxyUsersModel();
        $proxy_users = $ProxyUsersModel->info($pid);
        if ($proxy_users['proxy_id'] > 0) {
            return [
                'user_id' => $proxy_users['user_id'],
                'channel' => 1,
                'role_id' => $proxy_users['proxy_id'],
                'role_name' => $proxy_users['proxyLevel']['proxy_name']
            ];
        }
        if ($user['role_id'] > 0) {
            return $this->findLevel($user, $proxy_users['pid'], $time);
        }
        $user_info = $UsersModel->info($pid);
        if ($user_info['role_id'] > 0) {
            return [
                'user_id' => $user_info['user_id'],
                'channel' => 0,
                'role_id' => $user_info['role_id'],
                'role_name' => $user_info['role']['role_name']
            ];
        } else {
            return $this->findLevel($user, $proxy_users['pid'], $time);
        }
    }
}
